//
//  QuickLookViewController.m
//  quickLook
//
//  Created by J on 15/8/30.
//  Copyright (c) 2015年 JZJ. All rights reserved.
//

#import "QuickLookViewController.h"

#import "Header.h"
#import "RightSearchController.h"
#import "Model.h"

#import "QuickLookCell.h"

#import "WebViewController.h"

#import "TableViewController.h"

#import "LandController.h"




#import "RNFrostedSidebar.h"//侧拉

#import "SettingController.h"


#import "TableViewController.h"

#import "IndividualViewController.h"


@interface QuickLookViewController ()<RNFrostedSidebarDelegate,UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
{
    NSNumber*  _number;
    BOOL _isLoad;

    TableViewController* _leftVC;
    
    RNFrostedSidebar * _callout;
}

@property(nonatomic,assign)BOOL isLoad;
@property(nonatomic,strong)UIScrollView* scrollView;


@property(nonatomic,strong)UIView* bottomView;



@property(nonatomic,strong)UIButton* AttentionButton;//左


@property(nonatomic,strong)UIButton* recommandButton;//右



@end

@implementation QuickLookViewController

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];
    if (_scrollView.contentOffset.x<SCREEN_WIDTH) {
        [_leftVC loadData];

        
    }
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
    
    
//    self.navigationController.navigationBar.barTintColor=JZJYELLOW;
    NSUserDefaults* userdefault=[NSUserDefaults standardUserDefaults];
    
    BOOL isLand= [userdefault boolForKey:ISLAND];
    
    _leftVC.isLand=isLand;
    if (_leftVC.isLand) {
        
        [_leftVC loadData];
        [self loadData];
        
    }else{
        

        _leftVC.dataArray=nil;
        [_leftVC.tableView reloadData];
    }
    
    
    


   }


- (void)viewDidLoad {
    [super viewDidLoad];
    JZJLog(@"%@",self.view);
    
    _number = @0;
    // Do any additional setup after loading the view.
    self.view.backgroundColor=[UIColor whiteColor];
    _isLoad = NO;

 
    [self createUI];
    [self loadData];
//    UIImage* image=[[UIImage imageNamed:@"burger@2x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    UIImage* image=[[UIImage imageNamed:@"burger@2x.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(slide)];


    
    
    
}


//左侧弹出界面

- (void)slide{
    NSArray *images = @[
                        [UIImage imageNamed:@"profile@2x"],

                        [UIImage imageNamed:@"gear"],
                        [UIImage imageNamed:@"star@2x"],

                        ];
    
    NSArray *colors = @[
                        [UIColor colorWithRed:119/255.f green:152/255.f blue:255/255.f alpha:1],

                        [UIColor colorWithRed:240/255.f green:159/255.f blue:254/255.f alpha:1],
                        [UIColor colorWithRed:255/255.f green:137/255.f blue:167/255.f alpha:1],

                        ];
    
    
    RNFrostedSidebar *callout = [[RNFrostedSidebar alloc] initWithImages:images selectedIndices:nil borderColors:colors];
    _callout=callout;
    //    RNFrostedSidebar *callout = [[RNFrostedSidebar alloc] initWithImages:images];
    callout.delegate = self;
    //    callout.showFromRight = YES;
    
    UISwipeGestureRecognizer* swip=[[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swip:)];
    
    //增加右侧滑动返回
    swip.direction=UISwipeGestureRecognizerDirectionLeft;
    
    [callout.contentView addGestureRecognizer:swip];
    callout.contentView.userInteractionEnabled=YES;
    [callout show];
    
    
    
    
  
    
}



- (void)swip:(UISwipeGestureRecognizer*)swip
{
    
    if (swip.direction==UISwipeGestureRecognizerDirectionLeft) {
        [_callout dismiss];
    }
    
}

//设置scrollView是否允许被滑动
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    //拿到手指触摸在scrollView上的坐标
    CGPoint point = [gestureRecognizer locationInView:_callout.contentView];
    
    JZJLog(@"%zd",point.y);

    return NO;
}




#pragma mark - RNFrostedSidebarDelegate

- (void)sidebar:(RNFrostedSidebar *)sidebar didTapItemAtIndex:(NSUInteger)index {
    JZJLog(@"Tapped item at index %i",index);
   
    switch (index) {
        case 0:
        {
            
            IndividualViewController* vc=[[IndividualViewController alloc]init];
            vc.title=@"个人";
            [self.navigationController pushViewController:vc animated:YES];
            
            [sidebar dismiss];
           
        }
            break;
            
        case 1:
        {
            
            SettingController* vc=[[SettingController alloc]init];//设置页面
            
            [self.navigationController pushViewController:vc animated:YES];
            
            [sidebar dismiss];
            

            
        }
            break;
            
            
        case 2:
        {
            
            TableViewController* vc=[[TableViewController alloc]init];//收藏
            vc.title=@"关注专题";
            [self.navigationController pushViewController:vc animated:YES];
            
            [sidebar dismiss];

         
            
        }
            break;
    }

    
}

- (void)loadData{

    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    
    BOOL isConnection;

    isConnection=[userdefault boolForKey:ISCONNECTED];
    
    JZJLog(@"quicklook::%zd",isConnection);
    
    [DownLoad getQuickLookDataWithPageNumber:_number withBlock:^(id obj, NSError *error) {
        
        
        if (!obj) {
            [_tableView.header endRefreshing];
            [_tableView.footer endRefreshing];
            _isLoad=NO;
            return;
        }
        
        
        
        if ([_number isEqual:@0]) {
            //下拉刷新
            _dataArray=[NSMutableArray array];
            [_tableView.header endRefreshing];
            
            
        }else{
            [_tableView.footer endRefreshing];
        }

        
       

        NSArray* comics=  obj[@"data"][@"comics"];
        
        
        [comics enumerateObjectsUsingBlock:^(NSDictionary* dic, NSUInteger idx, BOOL *stop) {
            
            
            Model* model=[[Model alloc]init];

            [model setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:model];
            
            
        }];
        
        
        [_tableView reloadData];
        _isLoad=NO;//这是一个异步执行方法 当这个异步操作执行完毕之后 isLoad才会变成NO
    }];



    
    
}


- (void)createUI
{
    
    
    
    //titleView
    self.tableView.frame=CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-49);
    
    UIView* titleView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 50)];
    titleView.center=self.navigationController.navigationBar.center;
    UIButton* AttentionButton=[UIButton buttonWithType:UIButtonTypeCustom];
    AttentionButton.frame=CGRectMake(0, 0, 40, 30);

    [AttentionButton setTitle:@"关注" forState:UIControlStateNormal];
    
    [AttentionButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    [AttentionButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    [AttentionButton addTarget:self action:@selector(left:) forControlEvents:UIControlEventTouchUpInside];
    
    self.AttentionButton=AttentionButton;

    UIButton* recommandButton=[UIButton buttonWithType:UIButtonTypeCustom];
    recommandButton.frame=CGRectMake(50, 0, 40, 30);
    
    [recommandButton setTitle:@"推荐" forState:UIControlStateNormal];
    
    
    [recommandButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    
    [recommandButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    
    [recommandButton addTarget:self action:@selector(right:) forControlEvents:UIControlEventTouchUpInside];
    self.recommandButton=recommandButton;

    
    //滑动view
    UIView* bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, 30, 40, 5)];
    bottomView.backgroundColor=[UIColor grayColor];
    [titleView addSubview:bottomView];
    
    bottomView.layer.cornerRadius=3;
    [titleView addSubview:AttentionButton];
    
    
    [titleView addSubview:recommandButton];

    
    self.navigationItem.titleView=titleView;
    self.bottomView=bottomView;
    
    
    
    self.automaticallyAdjustsScrollViewInsets=NO;

    UIImage* image=[[[UIImage imageNamed:@"magnifier.png"]TransformtoSize:CGSizeMake(20, 20)]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(push)];
    
  
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    
    _tableView.delegate=self;
    _tableView.dataSource=self;
    
    
    
    _scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64-49)];
    
    _scrollView.contentSize=CGSizeMake(SCREEN_WIDTH*2, SCREEN_HEIGHT-64-49);
    _scrollView.pagingEnabled=YES;
    _scrollView.delegate=self;
    
    //添加tableView
    [_scrollView addSubview:_tableView];
    
    
    _scrollView.bounces=NO;
    

    [self.view addSubview:_scrollView];

    _scrollView.showsHorizontalScrollIndicator=NO;
    _scrollView.showsVerticalScrollIndicator=NO;
    _scrollView.contentOffset=CGPointMake(self.view.frame.size.width, 0);
    
    //左侧登陆控制器
    _leftVC=[[TableViewController alloc]init];
    //TODO:
    _leftVC.view.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49);
    _leftVC.delegate=self;
    
    
    
    
    
    
    _leftVC.view.backgroundColor=[UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1.0];
    [_scrollView addSubview:_leftVC.view];
    
    
    WS(weakSelf)

    
    
    //添加下拉刷新
    [_tableView addLegendHeaderWithRefreshingBlock:^{// 每次下拉都会产生效果  所以需要一次操作来停止效果
        if (!weakSelf.isLoad) {
            //开始数据请求
            _number=@0;
            weakSelf.isLoad=!weakSelf.isLoad;
            [weakSelf loadData];
        }
        else
        {
            [weakSelf.tableView.header endRefreshing];//如果正在运行 的时候拉一下会进入else但是 会产生效果   需要停止这个效果 每次下拉都会产生效果  所以需要一次操作来停止效果
            
        }
    }];
    
    
    
    
    //添加上拉加载
    [_tableView addLegendFooterWithRefreshingBlock:^{

        if (!weakSelf.isLoad)//如果没有加载为真 进入方法
        {
            _number=[NSNumber numberWithInteger:[_number integerValue]+20 ];
            weakSelf.isLoad=!weakSelf.isLoad;//加载状态
            [weakSelf loadData];//异步执行完完毕之后会变成未加载  否则再次下拉进入else方法
            
//            JZJLog(@"_number%zd",_number);
            
        }else{//异步请求执行完毕之后isLoad才会变成NO 否则再次下拉会一直执行这个方法
            [weakSelf.tableView.footer endRefreshing];
            
        }
        
        
    }];
    

}

#pragma mark --UITableViewDataSource


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    
    return _dataArray.count;
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 1;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    QuickLookCell* cell=[tableView dequeueReusableCellWithIdentifier:@"ID"];
    
    
    if (!cell) {
        
        cell=[[NSBundle mainBundle]loadNibNamed:@"QuickLookCell" owner:nil options:nil][0];
        
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.delegate=self;
    }

//    刷新cell

    cell.tag=indexPath.row+1000;
    Model* model=_dataArray[indexPath.section];
    
//    JZJLog(@"xxxxxx%zd",_number);

    [cell refreshWithModel:model WithIndexPath:indexPath];
    JZJLog(@"%zd",indexPath.section);
    
    return cell;

}


#pragma mark --UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 220;

}

- (void)push {

    
    RightSearchController* vc=[[RightSearchController alloc]init];
    
    vc.hidesBottomBarWhenPushed=YES;
    
    
    
    
    [self.navigationController pushViewController:vc animated:YES];
    
    

    
    
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    if (!section) {
        return 40;
    }
    return 9;

}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    UITableViewHeaderFooterView* view=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ID"];
    
    
    if (section==0) {
        if (!view) {
            
            
            view=[[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"ID"];
            
            UILabel* lable=[[UILabel alloc]initWithFrame:CGRectMake(30, 10, 100, 20)];
            lable.textColor=JZJGRAY;
            lable.text=@"今日推荐";
            lable.font= [UIFont boldSystemFontOfSize:15];
            [view.contentView addSubview:lable];
            
            UIImageView* imageView=[[UIImageView alloc]initWithFrame:CGRectMake(5, 10, 20, 20)];
            
            imageView.image=[UIImage imageNamed:@"headerViewIcon.png"];
            
            [view.contentView addSubview:imageView];
            
            
            
            
        }
        
        
        return view;
    }
   
    return nil;
}





- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    Model* model=_dataArray[indexPath.section];//tableview是分组的 所以改用分组形势

    WebViewController * vc=[[WebViewController alloc]init];
    
    
    vc.model=model;
    
    vc.hidesBottomBarWhenPushed=YES;
    
    [self.navigationController pushViewController:vc animated:YES];

}



- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
 CGRect frame=  _bottomView.frame;
    if (scrollView.contentOffset.x != 0) {
        //只有x发生变动的时候才改变frame

        
        frame=CGRectMake((scrollView.contentOffset.x/SCREEN_WIDTH)*frame.size.width, frame.origin.y, frame.size.width, frame.size.height);
        
        _bottomView.frame=frame;
    }



    
}



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger page=_scrollView.contentOffset.x/SCREEN_WIDTH;
    
    if (page==0) {
        
        [self leftAnimate];
        
    }else
    {
        
        
        [self rightAnimate];
        
    }
    



}


//关注
- (void)left:(UIButton*)sender

{

    
//    JZJLog(@"左");

    [self leftAnimate];
    

    _scrollView.contentOffset=CGPointMake(0, 0);
   

}

//推荐
- (void)right:(UIButton*)sender

{
//    JZJLog(@"右");

    _scrollView.contentOffset=CGPointMake(SCREEN_WIDTH, 0);

    [self rightAnimate];
    
   }


- (void)leftAnimate{
    
    
    [UIView animateWithDuration:0.1 animations:^{
        
        _bottomView.frame=CGRectMake(0, 30, 40, 5);
        
        
    }];
    
    [self.recommandButton setTitleColor:[UIColor grayColor] forState:normal];
    
    
    [self.AttentionButton setTitleColor:[UIColor blackColor] forState:normal];
    

    
}


- (void)rightAnimate{
    
    
    
    [UIView animateWithDuration:0.1 animations:^{
        
        
        _bottomView.frame=CGRectMake(50, 30, 40, 5);

        
        
    }];

    [self.AttentionButton setTitleColor:[UIColor grayColor] forState:normal];
    
    
    [self.recommandButton setTitleColor:[UIColor blackColor] forState:normal];
    
}



@end
